package com.nowcoder.community.controller;

import com.nowcoder.community.service.AlphaService;
import com.nowcoder.community.util.CommunityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

/**
 * @author AnYang
 * @Description TODO
 * @Version 1.0.0
 * @Date 2024/1/12
 */
@Controller
@RequestMapping("/alpha")
public class AlphaController {

    @Autowired
    private AlphaService alphaService;

    @RequestMapping("/hello")
    @ResponseBody
    public String hello() {
        return "Hello";
    }

    @RequestMapping("/data")
    @ResponseBody
    public String getData() {
        return alphaService.find();
    }

    //如何获取请求、响应数据
    //为什么是void，可以用responsebody对象直接向浏览器输出任何数据
    //dispatcherservlet调用这个方法时，dispatcherservlet会自动把请求、响应对象传递给方法
    @RequestMapping("/http")
    @ResponseBody
    public void http(HttpServletRequest request, HttpServletResponse response) {
        //获取请求方法
        System.out.println(request.getMethod());
        //获取路径
        System.out.println(request.getServletPath());
        //获取请求头的key，Enumeration和Iterator一样，不过年代更老
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            String value = request.getHeader(name);
            System.out.println(name + ": " + value);
        }
        //获取参数
        System.out.println(request.getParameter("code"));

        //返回响应数据
        response.setContentType("text/html;charset=utf-8");
        try (
                PrintWriter writer = response.getWriter()
        ){
            writer.write("<h1>牛客网<h1>");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // GET请求（简便）
    // /students?current=1&limit=20
    // 理论上url的参数和方法参数名一样，就可自动匹配，required：false代表url可以没有这个参数，defaultValue：默认
    @RequestMapping(path = "/students", method = RequestMethod.GET)
    @ResponseBody
    public String getStudents(
            @RequestParam(name = "current", required = false, defaultValue = "1") int current,
            @RequestParam(name = "limit", required = false, defaultValue = "10") int limit) {
        System.out.println(current);
        System.out.println(limit);
        return "some students";
    }

    // /students/123
    @RequestMapping(path = "/students/{id}", method = RequestMethod.GET)
    @ResponseBody
    public String getStudents(@PathVariable("id") int id) {
        System.out.println(id);
        return "a student";
    }

    @RequestMapping(path = "/student", method = RequestMethod.POST)
    @ResponseBody
    // post
    public String saveStudent(String name, int age) {
        System.out.println(name);
        System.out.println(age);
        return "success";
    }

    //响应HTML数据
    @RequestMapping(path = "/teacher", method = RequestMethod.GET)
    public ModelAndView getTeacher() {
        ModelAndView mav = new ModelAndView();
        //加入数据
        mav.addObject("name", "张三");
        mav.addObject("age", "12");
        //返回的页面
        mav.setViewName("/demo/view");
        return mav;
    }

    //第二种写法：dispatcherseverlet会将model赋值
    //不加ResponseBody默认是html
    @RequestMapping(path = "/school", method = RequestMethod.GET)
    public String getSchool(Model model) {
        model.addAttribute("name", "北京大学");
        model.addAttribute("age", "30");
        return "/demo/view";
    }

    //json异步请求
    //Java对象 -> JSON对象 -> JS对象
    //serverlet看到ResponseBody注解以及返回类型Map,会自动转化成json
    @RequestMapping(path = "/emp", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> getEmp() {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", 13);
        map.put("salary", 12343);
        return map;
    }

    //json异步请求
    @RequestMapping(path = "/emps", method = RequestMethod.GET)
    @ResponseBody
    public List<Map<String, Object>> getEmps() {
        List<Map<String, Object>> list = new ArrayList<>();

        Map<String, Object> map = new HashMap<>();
        map.put("name", "张三");
        map.put("age", 13);
        map.put("salary", 12343);
        list.add(map);

        map = new HashMap<>();
        map.put("name", "李四");
        map.put("age", 14);
        map.put("salary", 10000);
        list.add(map);

        map = new HashMap<>();
        map.put("name", "王五");
        map.put("age", 15);
        map.put("salary", 10000000);
        list.add(map);

        return list;
    }

    //cookie示例
    @RequestMapping(path = "/cookie/set", method = RequestMethod.GET)
    @ResponseBody
    public String setCookie(HttpServletResponse response) {
        // 创建cookie
        Cookie cookie = new Cookie("code", CommunityUtil.generateUUID());
        // 设置cookie生效的范围，可以节省资源，范围是/community/alpha这个路径及其子路径
        cookie.setPath("/community/alpha");
        // 设置cookie的有效时间，默认关闭浏览器就消失，设置时间后，会存在硬盘里，直到失效时间
        cookie.setMaxAge(60 * 10);
        // 发送cookie
        response.addCookie(cookie);

        return "set cookie";
    }

    //CookieValue获取特定cookie
    //缺点：存放在客户端，不安全，每次申请都会发送，浪费资源
    @RequestMapping(path = "/cookie/get", method = RequestMethod.GET)
    @ResponseBody
    public String getCookie(@CookieValue("code") String code) {
        System.out.println(code);
        return "get cookie";
    }

    // session示例
    @RequestMapping(path = "/session/set", method = RequestMethod.GET)
    @ResponseBody
    public String setSession(HttpSession session) {
        //springmvc 会自动创建session并注入进来
        session.setAttribute("id", 1);
        session.setAttribute("name", "TEST");
        return "set session";
    }

    @RequestMapping(path = "/session/get", method = RequestMethod.GET)
    @ResponseBody
    public String getSession(HttpSession session) {
        //springmvc 会自动创建session并注入进来
        System.out.println(session.getAttribute("id"));
        System.out.println(session.getAttribute("name"));
        return "get session";
    }

    // ajax示例
    @RequestMapping(path = "/ajax", method = RequestMethod.POST)
    @ResponseBody
    public String testAjax(String name, int age) {
        System.out.println(name +":"+ age);
        return CommunityUtil.getJSONString(0, "操作成功");
    }

}
